<template>
    <div class="order">
        <CheckItem :itemID="itemID" :show.sync="checkItemModal" :data="checkItem" @save="saveCheckItem"
                   :model="model"></CheckItem>
        <ItemDetail :loading="tableLoading" :show.sync="showModal" :value="item" title="Edit Item" :id="itemID"
                    @submit="confirmSubmit"
                    :action="action" :height="600" :arrow="questionnaires.length > 1" @arrow="changeItem"
                    :noSubmitRefresh="noSubmitRefresh"
                    :arrowCanPrevious="arrowCanPrevious" :arrowCanNext="arrowCanNext"></ItemDetail>
        <div class="row">
            <div class="col-md-12 p-0">
                <filter-form v-if="filters.length" :columns="filters" @submit="_submit">
                    <template slot="other_filter">
                        
                        <div class="row">
                            <div class="col-sm-4">
                                <VSelect v-model="currentTemplate" :options="templates"
                                         placeholder="template"></VSelect>
                            </div>
                            <div class="col-sm-4">
                                <VSelect :closeOnSelect="false" v-model="completedItems" :multiple="true" :options="items"  placeholder="Completed-Items"></VSelect>
                            </div>
                            <div class="col-sm-4">
                                <VSelect :closeOnSelect="false" v-model="notCompletedItems" :multiple="true" :options="items" placeholder="Not-Completed-Items"></VSelect>
                            </div>
                        </div>
                        <div style="margin: 10px 0;">CheckList Filter</div>
                    </template>
                </filter-form>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 bg-white p-0 m-0">
                <item-table title="Order List" :columns="defaultColumns" :data="data" :loading="tableLoading"
                            :page="page" :pageSize="pageSize" @sort="sort" :total="total" :model="model" isColumns
                            isExport @export="exportExcel"
                >
                    <template slot="logical_room__physical_room_id" slot-scope="props">
                        <div>
                            <span v-html="genPidLink(props.item.logical_room__physical_room_id)"></span>
                            <span style="margin-bottom: 6px;width: 6px;height: 6px; border-radius: 50%; display: inline-block;"
                                  :class="{'bg-success': props.item.room_service_status, 'bg-danger': !props.item.room_service_status}"></span>
                        </div>
                    </template>
                    <template slot="room_title" slot-scope="props">
                        <div class="td-ellipsis">
                            {{props.item.room_title}}
                        </div>
                        <i class="fif fif-ellipsis text-info" @click="showTdDetail(props.item.room_title)"></i>
                    </template>
                    <template slot="logical_room__physical_room__host_name" slot-scope="props">
                        <span>{{ genHostNameText(props.item.logical_room__physical_room__host_name) }}</span>
                    </template>
                    <template slot="logical_room_id_hook" slot-scope="props">
                        <a :href="`#/logicalroomcalendar/${props.item.logical_room_id_hook}`" target="_blank">
                            {{props.item.logical_room_id_hook}}
                        </a>
                    </template>
                    <template slot="actions" slot-scope="props">
                        <button type="button" class="btn btn-info btn-outline btn-circle btn-md m-r-5"
                                @click="_editItem(props)">
                            <i class="fif fif-edit"></i>
                        </button>

                        <button type="button" class="btn btn-success btn-outline btn-circle btn-md m-r-5"
                                @click="_question(props)">
                            <i class="fif fif-other-list"></i>
                        </button>

                        <button type="button" class="btn btn-primary btn-outline btn-circle btn-md m-r-5"
                                @click="checkList(props, model)"
                                :class="{'btn-warning': !props.item.check_lists.length}">
                            <i class="fif fif-check_list-border"></i>
                        </button>

                        <button type="button" class="btn btn-danger btn-outline btn-circle btn-md m-r-5"
                                @click="deleteItem(props)">
                            <i class="fif fif-delete"></i>
                        </button>

                    </template>
                </item-table>
                <v-paginate :pageCount="pageCount" :page="page" @change="changePage"></v-paginate>
            </div>
        </div>
    </div>
</template>

<script>
    // components
    import vPaginate from '@/components/widgets/Pagination'
    import ItemTable from '@/components/widgets/ItemTable'
    import ItemDetail from '@/components/widgets/ItemDetail'
    import FilterForm from '@/components/widgets/FilterForm'
    import VSelect from "vue-select"

    import CheckItem from '@/components/widgets/CheckItem'
    import {searchModel} from "@/api/model";
    // mixin
    import {lifeHookMixin, itemMixin, checkListMixin} from '@/mixins/item'
    import Config from "@/config"
    import columns from "@/config/columns"
    import {genUrlParams} from "@/utils"

    export default {
        name: "Order",
        components: {vPaginate, ItemTable, FilterForm, ItemDetail, CheckItem, VSelect},
        mixins: [lifeHookMixin, itemMixin, checkListMixin],
        data() {
            return {
                orderBy: '-gentime',
                questionnaires: [],
                questionnaireIndex: 0,
                noSubmitRefresh: false,

                searchLoading: false,
                templates: [],
                currentTemplate: null,
                items: [],
                completedItems: [],
                notCompletedItems: [],
            }
        },
        created() {
            searchModel('CheckList', {
                search_keys: {is_template: true},
                page_size: 999
            }).then(res => {
                this.templates = res.data.list.map(item => {
                   return {
                       label: item.name,
                       value: item.id
                   }
                })
            })
        },
        computed: {
            arrowCanPrevious() {
                let len = this.questionnaires.length
                return len > 1 && this.questionnaireIndex < len && this.questionnaireIndex > 0 ? true : false
            },
            arrowCanNext() {
                let len = this.questionnaires.length
                return len > 1 && this.questionnaireIndex < len - 1 ? true : false
            }
        },
        methods: {
            changeItem(dir) {
                this.questionnaireIndex = dir === "previous" ? this.questionnaireIndex - 1 : this.questionnaireIndex + 1
                let item = this.questionnaires[this.questionnaireIndex]
                this.model = item.model
                this.defaultColumns = columns[this.model]
                this.item = []
                this.editItem({item: {id: item.id}})
            },
            _submit(conditions, flag) {
                this.model = "Order"
                this.defaultColumns = columns[this.model]
                let extendedFilter = {}
                if (this.currentTemplate) {
                    extendedFilter = {template_id: this.currentTemplate.value}
                    if (this.completedItems.length) {
                        extendedFilter["completed"] = this.completedItems.map(item => item.label)
                    }
                    if (this.notCompletedItems.length) {
                        extendedFilter["not_completed"] = this.notCompletedItems.map(item => item.label)
                    }
                } else {
                    extendedFilter = {}
                }

                this.submit(conditions, flag, extendedFilter)
            },
            _question(props) {
                this.noSubmitRefresh = true
                this.questionnaireIndex = 0;
                this.questionnaires = []
                let pid = props.item.logical_room__physical_room_id
                if (pid) {
                    searchModel("PhysicalRoom", {
                        search_keys: {
                            physical_room_id: pid.trim()
                        },
                    }).then(res => {
                        if (res.data.list.length) {
                            return res.data.list[0]
                        } else {
                            this.model = "Order"
                            this.defaultColumns = columns[this.model]
                            $.toast({
                                heading: "This Order hasn't PhysicalRoom",
                                position: 'top-right',
                                icon: 'error'
                            })
                        }
                    }).then(room => {
                        if (Config.ROOM_AREA_JAPAN.indexOf(room.room_area.trim()) !== -1) {
                            this.model = "GuestRegistration"
                        } else if (Config.ROOM_AREA_THAILAND.indexOf(room.room_area.trim()) !== -1) {
                            this.model = "ThailandGuestRegistration"
                        } else {
                            $.toast({
                                heading: "The room area to which the order belongs is not in range",
                                position: 'top-right',
                                icon: 'error'
                            })
                            this.model = "Order"
                            this.defaultColumns = columns[this.model]
                            return
                        }
                        searchModel(this.model, {
                            search_keys: {
                                reservation_code__icontains: props.item.reservation_code
                            }
                        }).then(res => {
                            if (res.data.list.length) {
                                this.questionnaires = res.data.list.map(item => Object.assign({}, item, {model: this.model}))
                                this.defaultColumns = columns[this.model]
                                this.item = []
                                this.editItem({item: {id: this.questionnaires[0].id}})
                            } else {
                                if (this.model === "GuestRegistration") {
                                    let params = {
                                        reservation_code: props.item.reservation_code,
                                        guest_name: props.item.guest_name,
                                        checkin: props.item.checkin,
                                        checkout: props.item.checkout,
                                        platform: props.item.platform
                                    }
                                    if (props.item.checkin_time) {
                                        params["checkin_time"] = props.item.checkin_time
                                    }
                                    if (props.item.checkout_time) {
                                        params["checkout_time"] = props.item.checkout_time
                                    }

                                    swal({
                                        title: "No Questionnaire",
                                        text: "Do you want to add Questionnaire?",
                                        icon: "warning",
                                        dangerMode: true,
                                        buttons: true,
                                    }).then(will => {
                                        if (will) {
                                            setTimeout(function () {
                                                window.open("https://registration.heyakun.com/?" + genUrlParams(params))
                                            }, 500);
                                        }
                                    })
                                } else {
                                    let params = {
                                        reservation_code: props.item.reservation_code,
                                        guest_name: props.item.guest_name,
                                        checkin: props.item.checkin,
                                        guest_contact: props.item.guest_contact
                                    }
                                    swal({
                                        title: "No Questionnaire",
                                        text: "Do you want to add Questionnaire?",
                                        icon: "warning",
                                        dangerMode: true,
                                        buttons: true,
                                    }).then(will => {
                                        if (will) {
                                            setTimeout(function () {
                                                window.open("https://registration.heyakun.com/thailand/?" + genUrlParams(params))
                                            }, 500);
                                        }
                                    })

                                }

                                this.model = "Order"
                                this.defaultColumns = columns[this.model]
                            }
                        })
                    })
                } else {
                    this.model = "Order"
                    this.defaultColumns = columns[this.model]
                    $.toast({
                        heading: 'This Order hasn\'t PhysicalRoom',
                        position: 'top-right',
                        icon: 'error'
                    })
                }

            },
            _editItem(props) {
                this.noSubmitRefresh = false
                this.model = "Order"
                this.defaultColumns = columns[this.model]
                this.item = []
                this.editItem(props)
            },
            genHostNameText(str) {
                let arr = str ? str.split(';') : []
                let newArr = []
                for (let i in arr) {
                    if (newArr.indexOf(arr[i]) === -1) {
                        newArr.push(arr[i])
                    }
                }
                return newArr.join(';')
            },
            genPidLink(str) {
                let arr = str ? str.split(';') : []
                let a = ''
                for (let i in arr) {
                    let q = i == arr.length - 1 || arr.length == 1 ? '' : ';'
                    a += `<a href="#/physicalroomcalendar/${arr[i]}" target="_blank">${arr[i] + q}</a>`
                }
                return a
            },
        },
        watch: {
            showModal(val) {
                if (!val) {
                    this.model = "Order"
                    this.defaultColumns = columns[this.model]
                }
            },
            currentTemplate(val) {
                this.completedItems = []
                this.notCompletedItems = []
                if (val) {
                    searchModel("CheckListItem", {
                        search_keys: {
                            check_list_id: val.value
                        },
                        page_size: 999
                    }).then( res => {
                        this.items = res.data.list.map(item => {
                            return {
                                label: item.item_name,
                                value: item.id
                            }
                        })
                    } )
                } else {
                    this.items = []
                }
            },
        }
    }
</script>

<style lang="stylus">

</style>